package com.simple.api.serivce.impl;

import com.simple.api.base.entity.ResponseModel;
import com.simple.api.base.enums.StateCode;
import com.simple.api.base.ex.EEException;
import com.simple.api.serivce.FileDownloadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.logging.Logger;

@Service
public class FileDownloadServiceImpl implements FileDownloadService {

    private  static  Logger logger = Logger.getLogger(FileDownloadServiceImpl.class.getSimpleName());

    @Value("${file.path}")
    public String filepath;

    @Override
    public void downApkByStream(String filename, HttpServletResponse response) throws Exception {

        logger.info(filepath +" == "+filename);
        File dir = new File(filepath);
        FileInputStream fis = null;
        BufferedInputStream is = null;
        try {

            ServletOutputStream outputStream = response.getOutputStream();
            if (dir.exists()) {

                dir = new File(filepath, filename);

                if (dir.isFile() && dir.exists()) {
                    // 配置文件下载
                    response.setHeader("content-type", "application/octet-stream");
                    response.setHeader("Content-Length",dir.length()+"");
                    response.setContentType("application/octet-stream");
                    // 下载文件能正常显示中文
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

                    byte[] buffer = new byte[1024];


                        fis = new FileInputStream(dir);
                        is = new BufferedInputStream(fis);

                        int i = is.read(buffer);
                        while (i != -1) {
                            outputStream.write(buffer, 0, i);
                            i = is.read(buffer);
                        }
                        outputStream.flush();
                        logger.info("success");


                } else {
                    logger.info("file error");
                    throw new Exception("文件名错误或文件不存在");
                }

            } else {
               // outputStream.print("path error" + dir.exists() + "   " + dir.isDirectory() + " = " + dir.getPath());
                throw new Exception("路径不存在");
            }


        } catch (Exception e) {
            e.printStackTrace();
            throw new EEException(new ResponseModel(StateCode.OTHER_ERROR.code(),e.getMessage(),null));

        } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
         }

    }

    @Override
    public ResponseEntity<byte[]> downApkByResponseEntity(String filename) throws Exception{

        long startTime = System.currentTimeMillis();
        BufferedInputStream in = null;
        ByteArrayOutputStream byteArray = null;
        try {

            File dir = new File(filepath, filename);
            if (dir.isFile() && dir.exists()) {

                in = new BufferedInputStream(new FileInputStream(dir));
                byteArray = new ByteArrayOutputStream();
                // 请求体
                byte[] body = new byte[1024];
                int i = in.read(body);
                while (i != -1) {
                    byteArray.write(body, 0, i);
                    i = in.read(body);
                }

                body = byteArray.toByteArray();
                // 请求头
                HttpHeaders httpHeaders = new HttpHeaders();
                // 这里需对中文进行转码处理
                // 告诉浏览器弹出下载对话框
                httpHeaders.add("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"), "ISO-8859-1"));
                ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(body, httpHeaders, HttpStatus.OK);
                logger.info("download file total with ResponseEntity time : {}" + (System.currentTimeMillis() - startTime));
                return responseEntity;

            } else {
                throw new Exception("文件名错误或文件不存在");
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("transfer in error .");
            throw new EEException(new ResponseModel(StateCode.OTHER_ERROR.code(),e.getMessage(),null));

        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (byteArray != null) {
                try {
                    byteArray.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

    }

}
